<?php
/**
 * 平台红包模型
 * 
 * @copyright  Copyright (c) 中国追溯
 * @since      File available since Release v1.1
 */
defined('InShopNC') or exit('Access Invalid!');
class redpacketModel extends Model {
        
    const GETTYPE_DEFAULT        = 'points';//默认领取方式 
    const RPACKET_TYPE_GENERAL   = 1;  //红包类型：普通红包
    const RPACKET_TYPE_NEWBIE    = 2;  //红包类型：新人红包
    const RPACKET_TYPE_SHARE     = 3;  //红包类型：分享红包
    
    const RPACKET_GET_POINTS     = 1;  //红包领取方式: 积分兑换
    const RPACKET_GET_PWD        = 2;  //红包领取方式: 卡密兑换
    const RPACKET_GET_FREE       = 3;  //红包领取方式: 免费领取
    
    const RPACKET_STATE_USABLE   = 1;  //红包模板状态 : 有效
    const RPACKET_STATE_DISABLED = 2;  //红包模板状态 : 有效

    private $rpacket_sector;
    private $rpacket_place;
    private $redpacket_type_arr;
    private $gettype_arr;
    private $templatestate_arr;
    private $redpacket_state_arr;
    
    public function __construct(){
        parent::__construct();
        //红包需求部门
        $this->rpacket_sector = array(1=>'运营中心');
        //红包投放位置
        $this->rpacket_place = array(
                                        'all'    => array('sign' => 0, 'name' => '全部'),
                                        'pc'     => array('sign' => 1, 'name' => '电脑端'),
                                        'wap'    => array('sign' => 2, 'name' => 'wap端'),
                                        'applet' => array('sign' => 3, 'name' => '小程序端')
                                    );
        //红包类型
        $this->redpacket_type_arr = array('general' => array('sign' => 1, 'name' => '普通红包'), 'newbie' => array('sign' => 2, 'name' => '新人红包'), 'share' => array('sign' => 3, 'name' => '分享红包'));
        //红包领取方式
        $this->gettype_arr = array('points'=>array('sign'=>1,'name'=>'积分兑换'),'pwd'=>array('sign'=>2,'name'=>'卡密兑换'),'free'=>array('sign'=>3,'name'=>'免费领取'));
        //红包模板状态
        $this->templatestate_arr = array('usable'=>array('sign'=>self::RPACKET_STATE_USABLE, 'name'=>'有效'), 'disabled'=>array('sign'=>self::RPACKET_STATE_DISABLED, 'name'=>'失效'));
        //红包状态
        $this->redpacket_state_arr = array('unused'=>array('sign'=>1,'name'=>'未使用'),'used'=>array('sign'=>2,'name'=>'已使用'),'expire'=>array('sign'=>3,'name'=>'已过期'));
    }

    /**
     * 取得当前有效红包数量
     * @param int $member_id
     */
    public function getCurrentAvailableRedpacketCount($member_id) {
        $info = rcache($member_id, 'm_redpacket', 'redpacket_count');
        if (empty($info['redpacket_count']) && $info['redpacket_count'] !== 0) {
            $condition['rpacket_owner_id'] = $member_id;
            $condition['rpacket_end_date'] = array('gt',TIMESTAMP);
            $condition['rpacket_state'] = 1;
            $redpacket_count = $this->table('redpacket')->where($condition)->count();
            $redpacket_count = intval($redpacket_count);
            wcache($member_id, array('redpacket_count' => $redpacket_count), 'm_redpacket');
        } else {
            $redpacket_count = intval($info['redpacket_count']);
        }
        return $redpacket_count;
    }

    /**
     * 获取红包模板需求部门
     * @return array
     */
    public function getRpacketSector()
    {
        return $this->rpacket_sector;
    }

    /**
     * 获取红包模板投放位置
     * @return array
     */
    public function getrpacketPlace()
    {
        return $this->rpacket_place;
    }

    /**
     * 获取红包模板类型
     */
    /**
     * 获取红包模板类型
     * @param  boolean $if_change 是否转化
     * @return array
     */
    public function getRedpacketType($if_change = false)
    {
        return ($if_change !== false) ? array_column($this->redpacket_type_arr, 'name', 'sign') : $this->redpacket_type_arr;
    }
    /**
     * 获取红包模板状态数组
     */
    public function getTemplateState(){
        return $this->templatestate_arr;
    }
    /**
     * 获取红包状态数组
     */
    public function getRedpacketState(){
        return $this->redpacket_state_arr;
    }
    /**
     * 返回红包领取方式数组
     * @return array
     */
    public function getGettypeArr() {
        return $this->gettype_arr;
    }
    /**
     * 新增红包模板
     */
    public function addRptTemplate($param){
        if(!$param){
        	return false;
        }
        return $this->table('redpacket_template')->insert($param);
    }
    /**
     * 查询红包模板列表
     */
    public function getRptTemplateList($where, $field = '*', $limit = 0, $page = 0, $order = '', $group = '') {
        $list = array();
        if (is_array($page)){
            if ($page[1] > 0){
                $list = $this->table('redpacket_template')->field($field)->where($where)->limit($limit)->page($page[0],$page[1])->order($order)->group($group)->select();
            } else {
                $list = $this->table('redpacket_template')->field($field)->where($where)->limit($limit)->page($page[0])->order($order)->group($group)->select();
            }
        } else {
            $list = $this->table('redpacket_template')->field($field)->where($where)->limit($limit)->page($page)->order($order)->group($group)->select();
        }
        //会员级别
        $member_grade = Model('member')->getMemberGradeArr();
        //后台管理员
        $admin_lists = Model('admin')->table('admin')->field('admin_id,admin_name')->select();
        $admin_lists = array_column($admin_lists, 'admin_name', 'admin_id');

        if (!empty($list) && is_array($list)){
            //转化后的投放位置标识
            $rpacket_place = array_column($this->rpacket_place, 'name', 'sign');
            //红包类型
            $rpacket_type = $this->getRedpacketType(true);
            
            foreach ($list as $k=>$v){
                if (!empty($v['rpacket_t_customimg'])){
                    $v['rpacket_t_customimg_url'] = UPLOAD_SITE_URL.DS.ATTACH_REDPACKET.DS.$v['rpacket_t_customimg'];
                }else{
                    $v['rpacket_t_customimg_url'] = UPLOAD_SITE_URL.DS.defaultGoodsImage(240);
                }
                //需求部门
                if (isset($v['rpacket_t_sector'])) {
                    $v['rpacket_t_sector_text'] = isset($this->rpacket_sector[$v['rpacket_t_sector']]) ? $this->rpacket_sector[$v['rpacket_t_sector']] : 'unknown';
                }
                //投放位置
                if (isset($v['rpacket_t_place'])) {
                    $v['rpacket_t_place_text'] = isset($rpacket_place[$v['rpacket_t_place']]) ? $rpacket_place[$v['rpacket_t_place']] : 'unknown';
                }
                //红包类型
                if (isset($v['rpacket_t_type'])) {
                    $v['rpacket_t_type_text'] = isset($rpacket_type[$v['rpacket_t_type']]) ? $rpacket_type[$v['rpacket_t_type']] : 'unknown';
                }
                //红包面额
                $v['price_text'] = (isset($v['rpacket_t_price_type']) && ($v['rpacket_t_price_type'] == '1')) ? $v['rpacket_t_price'] : $v['rpacket_t_price_state'] . ' - ' . $v['rpacket_t_price_end'];

                //红包使用情况 rpacket_use_situation - 可发送/已发送/已使用
                $v['rpacket_use_situation'] = $v['rpacket_t_total'] . '/' . $v['rpacket_t_giveout'] . '/' . $v['rpacket_t_used'];
                //活动有效期 rpacket_activity_validity - rpacket_t_start_date/rpacket_t_end_date
                $v['rpacket_activity_validity'] = date('Y-m-d', $v['rpacket_t_start_date']) . '/' . date('Y-m-d', $v['rpacket_t_end_date']);
                //红包有效期
                $v['rpacket_redpacket_validity'] = (isset($v['rpacket_t_validity']) && !empty($v['rpacket_t_validity'])) ? '领取后' . $v['rpacket_t_validity'] . '天内有效' : $v['rpacket_activity_validity'];

                //领取方式
                if($v['rpacket_t_gettype']){
                    foreach($this->gettype_arr as $gtype_k=>$gtype_v){
                        if($v['rpacket_t_gettype'] == $gtype_v['sign']){
                            $v['rpacket_t_gettype_key'] = $gtype_k;
                            $v['rpacket_t_gettype_text'] = $gtype_v['name'];
                        }
                    }
                }
                //状态
                if($v['rpacket_t_state']){
                    foreach($this->templatestate_arr as $tstate_k=>$tstate_v){
                        if($v['rpacket_t_state'] == $tstate_v['sign']){
                            $v['rpacket_t_state_text'] = $tstate_v['name'];
                        }
                    }
                }
                //会员等级
                $v['rpacket_t_mgradelimittext'] = $member_grade[$v['rpacket_t_mgradelimit']]['level_name'];
                
                //创建人
                if(isset($v['rpacket_t_adminid'])) $v['rpacket_t_admin_name'] = isset($admin_lists[$v['rpacket_t_adminid']]) ? $admin_lists[$v['rpacket_t_adminid']] : 'unknown';

                $list[$k] = $v;
            }
        }
        return $list;
    }
    /**
     * 获得红包模板详情
     */
    public function getRptTemplateInfo($where = array(), $field = '*', $order = '',$group = '') {
        $info = $this->table('redpacket_template')->where($where)->field($field)->order($order)->group($group)->find();
        if (!$info){
        	return array();
        }
        if($info['rpacket_t_gettype']){
            foreach($this->gettype_arr as $k=>$v){
                if($info['rpacket_t_gettype'] == $v['sign']){
                    $info['rpacket_t_gettype_key'] = $k;
                    $info['rpacket_t_gettype_text'] = $v['name'];
                }
            }
        }
        if($info['rpacket_t_state']){
            foreach($this->templatestate_arr as $k=>$v){
                if($info['rpacket_t_state'] == $v['sign']){
                    $info['rpacket_t_state_text'] = $v['name'];
                }
            }
        }

        //红包图片
        if (isset($info['rpacket_t_customimg'])) {
            $info['rpacket_t_customimg_url'] = empty($info['rpacket_t_customimg']) ? UPLOAD_SITE_URL.DS.defaultGoodsImage(240) : UPLOAD_SITE_URL.DS.ATTACH_REDPACKET.DS.$info['rpacket_t_customimg'];
        }

        //需求部门
        if (isset($info['rpacket_t_sector'])) {
            $info['rpacket_t_sector_text'] = isset($this->rpacket_sector[$info['rpacket_t_sector']]) ? $this->rpacket_sector[$info['rpacket_t_sector']] : 'unknown';
        }
        //投放位置
        if (isset($info['rpacket_t_place'])) {
            $rpacket_place = array_column($this->rpacket_place, 'name', 'sign');
            $info['rpacket_t_place_text'] = isset($rpacket_place[$info['rpacket_t_place']]) ? $rpacket_place[$info['rpacket_t_place']] : 'unknown';
        }
        //红包类型
        if (isset($info['rpacket_t_type'])) {
            $rpacket_type = array_column($this->redpacket_type_arr, 'name', 'sign');
            $info['rpacket_t_type_text'] = isset($rpacket_type[$info['rpacket_t_type']]) ? $rpacket_type[$info['rpacket_t_type']] : 'unknown';   
        }

        //活动有效期 rpacket_activity_validity - rpacket_t_start_date/rpacket_t_end_date
        if (isset($info['rpacket_t_start_date']) && isset($info['rpacket_t_end_date'])) {
            $info['rpacket_activity_validity'] = date('Y-m-d', $info['rpacket_t_start_date']) . '/' . date('Y-m-d', $info['rpacket_t_end_date']);
            //红包有效期
            $info['rpacket_redpacket_validity'] = (isset($info['rpacket_t_validity']) && !empty($info['rpacket_t_validity'])) ? '领取后' . $info['rpacket_t_validity'] . '天内有效' : $info['rpacket_activity_validity'];
        }

        //红包面额
        if (isset($info['rpacket_t_price'])) {
            $info['price_text'] = (isset($info['rpacket_t_price_type']) && ($info['rpacket_t_price_type'] == '1')) ? $info['rpacket_t_price'] : $info['rpacket_t_price_state'] . ' - ' . $info['rpacket_t_price_end'];
        }

        //会员等级
        if (isset($info['rpacket_t_mgradelimit'])) {
            $member_grade = Model('member')->getMemberGradeArr();
            $info['rpacket_t_mgradelimittext'] = $member_grade[$info['rpacket_t_mgradelimit']]['level_name'];
        }

        return $info;
    }
    
    /**
     * 更新红包模板信息
     * @param array $data
     * @param array $condition
     */
    public function editRptTemplate($where,$data) {
        return $this->table('redpacket_template')->where($where)->update($data);
    }
    
    /**
     * 删除红包模板信息
     * @param array $data
     * @param array $condition
     */
    public function dropRptTemplate($where) {
        $info = $this->getRptTemplateInfo($where);
        if (!$info){
        	return false;
        }
        $result = $this->table('redpacket_template')->where($where)->delete($where);
        if ($result){
            //删除旧图片
            if ($info['rpacket_t_customimg'] && is_file(BASE_UPLOAD_PATH . '/' . ATTACH_REDPACKET . '/' . $info['rpacket_t_customimg'])) {
                @unlink(BASE_UPLOAD_PATH . '/' . ATTACH_REDPACKET . '/' . $info['rpacket_t_customimg']);
                @unlink(BASE_UPLOAD_PATH . '/' . ATTACH_REDPACKET . '/' . str_ireplace('.', '_small.', $info['rpacket_t_customimg']));
            }
        }
        return $result;
    }
    
    /*
     * 获取红包编码
     * */
    public function get_rpt_code($member_id = 0){
        static $num = 1;
        $sign_arr = array();
        $sign_arr[] = sprintf('%02d',mt_rand(10,99));
        $sign_arr[] = sprintf('%03d', (float) microtime() * 1000);
        $sign_arr[] = sprintf('%010d',time() - 946656000);
        if($member_id){
            $sign_arr[] = sprintf('%03d', (int) $member_id % 1000);
        } else {
            //自增变量
            $tmpnum = 0;
            if ($num > 99){
                $tmpnum = substr($num, -1, 2);
            } else {
                $tmpnum = $num;
            }
            $sign_arr[] = sprintf('%02d',$tmpnum);
            $sign_arr[] = mt_rand(1,9);
        }
        $code = implode('',$sign_arr);
        $num += 1;
        return $code;
    }

    /**
     * 返回当前可用的红包列表,每种类型(模板)的红包里取出一个红包(同一个模板所有码面额和到期时间都一样)
     * @param array $condition 条件
     * @param array $goods_total 商品总金额
     * @return string
     */
    public function getCurrentAvailableRpt($condition = array(), $goods_total = 0, $order = '') {
        $condition['rpacket_end_date'] = array('egt',TIMESTAMP);
        $condition['rpacket_start_date'] = array('elt',TIMESTAMP);
        $condition['rpacket_state'] = 1;
        $rpt_list = $this->table('redpacket')->field('rpacket_id,rpacket_end_date,rpacket_price,rpacket_limit,rpacket_t_id,rpacket_code,rpacket_owner_id')->where($condition)->order($order)->key('rpacket_t_id')->select();
        foreach ($rpt_list as $key => $rpt) {
            if ($goods_total > 0 && $goods_total < $rpt['rpacket_limit']) {
                unset($rpt_list[$key]);
            } else {
                $rpt_list[$key]['desc'] = sprintf('%s元红包 有效期至 %s',$rpt['rpacket_price'],date('Y-m-d',$rpt['rpacket_end_date']));
                if ($rpt['rpacket_limit'] > 0) {
                    $rpt_list[$key]['desc'] .= sprintf(' 消费满%s可用',$rpt['rpacket_limit']);
                }

            }
        }
        return $rpt_list;
    }

    /**
     * 生成红包卡密
     */
    public function create_rpt_pwd($t_id) {
        if($t_id <= 0){
            return false;
        }
        static $num = 1;
        $sign_arr = array();
        //时间戳
        $time_tmp = uniqid('', true);
        $time_tmp = explode('.',$time_tmp);
        $sign_arr[] = substr($time_tmp[0], -1, 4).$time_tmp[1];
        //自增变量
        $tmpnum = 0;
        if ($num > 999){
            $tmpnum = substr($num, -1, 3);
        } else {
            $tmpnum = $num;
        }
        $sign_arr[] = sprintf('%03d',$tmpnum);
        //红包模板ID
        if($t_id > 9999){
            $t_id = substr($num, -1, 4);
        }
        $sign_arr[] = sprintf('%04d',$t_id);
        //随机数
        $sign_arr[] = sprintf('%04d',rand(1,9999));
        $pwd = implode('',$sign_arr);
        $num += 1;
        return array(md5($pwd), encrypt($pwd));
    }
    /**
     * 获取红包卡密
     */
    public function get_rpt_pwd($pwd) {
        if (!$pwd){
            return '';
        }
        $pwd = decrypt($pwd);
        $pattern = "/^([0-9]{20})$/i";
        if (preg_match($pattern, $pwd)){
            return $pwd;
        } else {
            return '';
        }
    }
    /**
     * 批量增加红包
     */
    public function addRedpacketBatch($insert_arr){
        return $this->table('redpacket')->insertAll($insert_arr);
    }
    /**
     * 增加红包
     */
    public function addRedpacket($insert_arr){
        return $this->table('redpacket')->insert($insert_arr);
    }
    /**
     * 获得红包列表
     */
    public function getRedpacketList($where, $field = '*', $limit = 0, $page = 0, $order = '', $group = ''){
        $list = array();
        if (is_array($page)){
            if ($page[1] > 0){
                $list = $this->table('redpacket')->field($field)->where($where)->limit($limit)->page($page[0],$page[1])->order($order)->group($group)->select();
            } else {
                $list = $this->table('redpacket')->field($field)->where($where)->limit($limit)->page($page[0])->order($order)->group($group)->select();
            }
        } else {
            $list = $this->table('redpacket')->field($field)->where($where)->limit($limit)->page($page)->order($order)->group($group)->select();
        }

        if (!empty($list) && is_array($list)){
            //根据订单支付单号找出列出订单相关信息
            $rpacket_order_ids = array_column($list, 'rpacket_order_id', 'rpacket_id');
            $redpacket_extend = Model('order')->viaPaysnGetOrderExtendInfo($rpacket_order_ids);
            foreach ($list as $k=>$v){
                if (!empty($v['rpacket_customimg'])){
                    $v['rpacket_customimg_url'] = UPLOAD_SITE_URL.DS.ATTACH_REDPACKET.DS.$v['rpacket_customimg'];
                }else{
                    $v['rpacket_customimg_url'] = UPLOAD_SITE_URL.DS.defaultGoodsImage(240);
                }
                foreach ($this->redpacket_state_arr as $state_k=>$state_v){
                    if ($state_v['sign'] == $v['rpacket_state']){
                    	$v['rpacket_state_text'] = $state_v['name'];
                    	$v['rpacket_state_key'] = $state_k;
                    }
                }
                $v['rpacket_start_date_text'] = @date('Y-m-d',$v['rpacket_start_date']);
                $v['rpacket_end_date_text'] = @date('Y-m-d',$v['rpacket_end_date']);
                //红包扩展信息
                $extend_info = isset($redpacket_extend[$v['rpacket_order_id']]) ? $redpacket_extend[$v['rpacket_order_id']] : array();
                $v['order_sns'] = isset($extend_info['order_sns']) ? $extend_info['order_sns'] : '';
                $v['add_time'] = isset($extend_info['add_time']) ? date('Y-m-d H:i:s', $extend_info['add_time']) : '';
                $v['buyer_name'] = isset($extend_info['buyer_name']) ? $extend_info['buyer_name'] : '';
                $v['pay_order'] = (isset($extend_info['pay_amount']) && isset($extend_info['goods_amount'])) ? $extend_info['goods_amount'] . '/' . $extend_info['pay_amount'] : '';
                $v['store_num'] = isset($extend_info['store_num']) ? $extend_info['store_num'] : '';
                $v['order_goods_sum'] = isset($extend_info['order_goods_sum']) ? $extend_info['order_goods_sum'] : '';
                $list[$k] = $v;
            }
        }
        return $list;
    }
    



    /**
     * 获得红包详情
     */
    public function getRedpacketInfo($where = array(), $field = '*', $order = '',$group = '') {
        $info = $this->table('redpacket')->where($where)->field($field)->order($order)->group($group)->find();
        if($info['rpacket_state']){
            foreach ($this->redpacket_state_arr as $state_k=>$state_v){
                if ($state_v['sign'] == $info['rpacket_state']){
                    $info['rpacket_state_text'] = $state_v['name'];
                    $info['rpacket_state_key'] = $state_k;
                }
            }
            if (!empty($info['rpacket_customimg'])){
                $info['rpacket_customimg_url'] = UPLOAD_SITE_URL.DS.ATTACH_REDPACKET.DS.$info['rpacket_customimg'];
            }else{
                $info['rpacket_customimg_url'] = UPLOAD_SITE_URL.DS.defaultGoodsImage(240);
            }
        }
        return $info;
    }
    /**
     * 更新过期红包状态
     */
    public function updateRedpacketExpire($member_id){
        $where = array();
        $where['rpacket_owner_id'] = $member_id;
        $where['rpacket_state'] = $this->redpacket_state_arr['unused']['sign'];
        $where['rpacket_end_date'] = array('lt', TIMESTAMP);
        $this->table('redpacket')->where($where)->update(array('rpacket_state'=>$this->redpacket_state_arr['expire']['sign']));
        //清空缓存
        dcache($member_id, 'm_redpacket');
    }
    
    /**
     * 获得推荐的红包列表
     * @param int $num 查询条数
     */
    public function getRecommendRpt($num){
        //查询推荐的热门红包列表
        $where = array();
        $where['rpacket_t_state'] = $this->templatestate_arr['usable']['sign'];
        //领取方式为积分兑换
        $where['rpacket_t_gettype'] = $this->gettype_arr['points']['sign'];
        //$where['rpacket_t_start_date'] = array('elt',time());
        $where['rpacket_t_end_date'] = array('egt',time());
        $recommend_rpt = $this->getRptTemplateList($where, $field = '*', $num, 0, 'rpacket_t_recommend desc,rpacket_t_id desc');
        return $recommend_rpt;
    }
    /**
     * 获得红包总数量
     */
    public function getRedpacketCount($where, $group = ''){
        return $this->table('redpacket')->where($where)->group($group)->count();
    }
    
    /**
     * 更新红包信息
     * @param array $data
     * @param array $condition
     */
    public function editRedpacket($where, $data, $member_id = 0) {
        $result = $this->table('redpacket')->where($where)->update($data);
        if ($result && $member_id > 0){
            wcache($member_id, array('redpacket_count' => null), 'm_redpacket');
        }
        return $result;
    }
    
    /**
     * 查询可兑换红包模板详细信息 -- 积分兑换红包 / 免费领取红包 （卡密红包不能使用该函数）
     */
    public function getCanChangeTemplateInfo($tid, $member_id, $redpacket_share_secretkey=null){
        if ($tid <= 0 || $member_id <= 0){
            return array('state'=>false,'msg'=>'参数错误');
        }
        //查询可用红包模板
        $where = array();
        $where['rpacket_t_id']          = $tid;
        $where['rpacket_t_state']       = self::RPACKET_STATE_USABLE;
        $where['rpacket_t_start_date']  = array('elt', TIMESTAMP);
        $where['rpacket_t_end_date']    = array('egt', TIMESTAMP);
        $template_info = $this->getRptTemplateInfo($where);
        if (empty($template_info) || $template_info['rpacket_t_total'] <= $template_info['rpacket_t_giveout']){//红包不存在或者已兑换完
            return array('state'=>false, 'msg'=>'红包已兑换完');
        }

        //如果红包类型是新人红包的话，校验该用户是否具有领取权限
        if (isset($template_info['rpacket_t_type']) && ($template_info['rpacket_t_type'] == self::RPACKET_TYPE_NEWBIE)) {
            $newbie_jurisdiction = $this->newbieRedpacketJurisdiction($member_id);
            if ($newbie_jurisdiction['state'] !== true) return array('state'=>false,'msg'=>$newbie_jurisdiction['msg']);
        }
        //如果红包类型是分享红包，校验该用户是否具有领取权限
        if (isset($template_info['rpacket_t_type']) && ($template_info['rpacket_t_type'] == self::RPACKET_TYPE_SHARE) ) {
            if( $template_info['rpacket_t_eachlimit'] > 0 ){
                $share_jurisdiction = $this->shareRedpacketJurisdiction($member_id, $tid, $redpacket_share_secretkey);
                if ($share_jurisdiction['state'] !== true) return array('state'=>false,'msg'=>$share_jurisdiction['msg']);
            }
            $isExiststRed = $this->getRedpacketInfo(array('rpacket_t_id'=>$tid,'rpacket_owner_id'=>$member_id,'redpacket_share_secretkey'=>$redpacket_share_secretkey));
            if($isExiststRed) return array('state'=>false,'msg'=>'你已领过该红包');

        }

        //如果红包领取方式是卡密兑换，直接返回错误
        if ($template_info['rpacket_t_gettype'] == self::RPACKET_GET_PWD) {
            return array('state'=>false,'msg'=>'抱歉，卡密红包模板不能直接兑换');
        }

        $model_member = Model('member');
        $member_info = $model_member->getMemberInfoByID($member_id);
        if (empty($member_info)){
            return array('state'=>false,'msg'=>'不存在该会员');
        }
        //验证会员积分是否足够
        if ($template_info['rpacket_t_gettype'] == $this->gettype_arr['points']['sign'] && $template_info['rpacket_t_points'] > 0){
            if (intval($member_info['member_points']) < intval($template_info['rpacket_t_points'])){
                return array('state'=>false,'msg'=>'您的积分不足，暂时不能兑换该红包');
            }
        }
        //验证会员级别
        $member_currgrade = $model_member->getOneMemberGrade(intval($member_info['member_exppoints']));
        $member_info['member_currgrade'] = $member_currgrade?$member_currgrade['level']:0;
        if ($member_info['member_currgrade'] < intval($template_info['rpacket_t_mgradelimit'])){
            return array('state'=>false,'msg'=>'您的会员级别不够，暂时不能兑换该红包');
        }

        //检查红包兑换次数     
        //查询红包列表
        $where = array();
        $where['rpacket_t_id']      = $tid;
        $where['rpacket_owner_id']  = $member_id;
        $redpacket_count = $this->getRedpacketCount($where);
        //同一张红包最多能兑换的次数
        if (intval($template_info['rpacket_t_eachlimit']) > 0 && $redpacket_count >= intval($template_info['rpacket_t_eachlimit'])){
            $message = sprintf('该红包您已兑换%s次，不可再兑换了',$template_info['rpacket_t_eachlimit']);
            return array('state'=>false,'msg'=>$message);
        }

        return array('state'=>true,'info'=>$template_info);
    }
    
    /**
     * 积分兑换红包 / 免费领取红包 （卡密红包不能使用该函数）
     */
    public function exchangeRedpacket($template_info, $member_id, $member_name = ''){
        if (intval($member_id) <= 0 || empty($template_info)){
            return array('state'=>false, 'msg'=>'参数错误');
        }
        //查询会员信息
        if (!$member_name){
            $member_info = Model('member')->getMemberInfoByID($member_id);
            if (empty($member_info)){
                return array('state'=>false, 'msg'=>'不存在该会员');
            }
            $member_name = $member_info['member_name'];
        }
        //添加红包信息
        $insert_arr = array();
        $insert_arr['rpacket_code'] = $this->get_rpt_code($member_id);
        $insert_arr['rpacket_t_id'] = $template_info['rpacket_t_id'];
        $insert_arr['rpacket_place'] = (int)$template_info['rpacket_t_place'];
        $insert_arr['rpacket_title'] = $template_info['rpacket_t_title'];
        $insert_arr['rpacket_desc'] = $template_info['rpacket_t_desc'];

        //确定红包有效期
        $rpacket_t_validity = isset($template_info['rpacket_t_validity']) ? (int)$template_info['rpacket_t_validity'] : 0;
        $rpacket_start_date = $template_info['rpacket_t_start_date'];  //默认模板起始有效期
        $rpacket_end_date = $template_info['rpacket_t_end_date'];  //默认模板结束有效期
        if ($rpacket_t_validity) {
            $rpacket_start_date = TIMESTAMP;
            $rpacket_end_date = 86400 * $rpacket_t_validity + TIMESTAMP;
        }

        $insert_arr['rpacket_start_date'] = $rpacket_start_date;
        $insert_arr['rpacket_end_date'] = $rpacket_end_date;

        //红包类型
        $rpacket_t_type = isset($template_info['rpacket_t_type']) ? (int) $template_info['rpacket_t_type'] : 0;
        $rpacket_type = $this->getRedpacketType(true);
        if (!isset($rpacket_type[$rpacket_t_type])) return array('state'=>false, 'msg'=>'红包类型错误');
        $insert_arr['rpacket_type'] = $rpacket_t_type;

        //确定红包领取方式
        $rpacket_t_gettype = isset($template_info['rpacket_t_gettype']) ? (int) $template_info['rpacket_t_gettype'] : 0;
        if (!$rpacket_t_gettype) return array('state'=>false, 'msg'=>'红包领取方式错误');

        //领取方式若不为免费领取，积分领取直接返回错误
        if (!in_array($rpacket_t_gettype, [self::RPACKET_GET_POINTS, self::RPACKET_GET_FREE], true)) return array('state'=>false, 'msg'=>'该方式只允许免费，积分领取红包');

        //确定红包面额
        $rpacket_t_price_type = isset($template_info['rpacket_t_price_type']) ? (int)$template_info['rpacket_t_price_type'] : 1;
        $rpacket_price = $template_info['rpacket_t_price'];  //默认红包模板额度

        //卡密红包,分享红包不随机金额
        if (($rpacket_t_price_type === 2) && ($rpacket_t_gettype !== self::RPACKET_GET_PWD) && ($rpacket_t_type !== self::RPACKET_TYPE_SHARE)) {
            $rpacket_t_price_state = isset($template_info['rpacket_t_price_state']) ? abs($template_info['rpacket_t_price_state']) * 100 : 0;
            $rpacket_t_price_end = isset($template_info['rpacket_t_price_end']) ? abs($template_info['rpacket_t_price_end']) * 100 : 0;
            if ($rpacket_t_price_state > $rpacket_t_price_end) return array('state'=>false,'msg'=>'红包随机额度错误');
            $rpacket_price = mt_rand($rpacket_t_price_state, $rpacket_t_price_end) / 100;
        }
        $insert_arr['rpacket_price'] = $rpacket_price;
        $insert_arr['rpacket_limit'] = $template_info['rpacket_t_limit'];
        $insert_arr['rpacket_state'] = $this->redpacket_state_arr['unused']['sign'];
        $insert_arr['rpacket_active_date'] = time();
        $insert_arr['rpacket_owner_id'] = $member_id;
        $insert_arr['rpacket_owner_name'] = $member_name;
        $insert_arr['rpacket_customimg'] = $template_info['rpacket_t_customimg'];
        $insert_arr['redpacket_share_secretkey'] = $template_info['redpacket_share_secretkey'];/*防止用户重复获取该红包*/
        $rpacket_id = $this->addRedpacket($insert_arr);
        if (!$rpacket_id){
            return array('state'=>false,'msg'=>'兑换失败');
        }
        //扣除会员积分
        if ($template_info['rpacket_t_points'] > 0 && $rpacket_t_gettype == $this->gettype_arr['points']['sign']){
            $points_arr['pl_memberid'] = $member_id;
            $points_arr['pl_membername'] = $member_name;
            $points_arr['pl_points'] = -$template_info['rpacket_t_points'];
            $points_arr['pl_desc'] = '红包'.$insert_arr['rpacket_code'].'消耗积分';
            $result = Model('points')->savePointsLog('app',$points_arr,true);
            if (!$result){
                return array('state'=>false,'msg'=>'兑换失败');
            }
        }
        if ($rpacket_id){
            //红包模板的兑换数增加
            $result = $this->editRptTemplate(array('rpacket_t_id'=>$template_info['rpacket_t_id']), array('rpacket_t_giveout'=>array('exp','rpacket_t_giveout+1')));
            if (!$result){
                return array('state'=>false,'msg'=>'兑换失败');
            }
            wcache($member_id, array('redpacket_count' => array('exp','redpacket_count+1')), 'm_redpacket');
            return array('state'=>true, 'msg'=>'兑换成功', 'rpacket_id' => $rpacket_id);
        } else {
            return array('state'=>false,'msg'=>'兑换失败');
        }
    }

    /**
     * 是否具有领取分享红包的权限
     * @param  int $member_id 会员id
     * @param  int $rpacket_t_id 红包模板
     * @return array
     */
    public function shareRedpacketJurisdiction($member_id, $rpacket_t_id, $redpacket_share_secretkey=null)
    {
        $result = ['state' => false, 'msg' => '未知错误'];
        //检查红包限制
        $astrict_state = $this->checkShareRedpacketNumberAstrictShare($member_id, $rpacket_t_id);
        if ($astrict_state === false) {
            $result['msg'] = $this->getErrorInfo();
            return $result;
        }
        return ['state' => true, 'msg' => '可以领取'];
    }

    /**
     * 检查分享红包的次数限制 -- 分享次数决定额度
     * @return false - 超限/ int - 可领取额度
     */
    public function checkShareRedpacketNumberAstrictShare($member_id = 0, $rpacket_t_id = 0)
    {
        $result = false;
        $model_redacket_share = Model('redpacket_share');
        //查询该用户分享该红包模板多少次
        $map = array(
            'member_id' => (int)$member_id,
            'rpacket_t_id' => (int)$rpacket_t_id
        );
        $share_number = $model_redacket_share->getOneData($map, 'share_number');
        $share_number = isset($share_number['share_number']) ? (int)$share_number['share_number'] : 1;

        //查询该用户领取了多少红包
        $where = array();
        $where['rpacket_t_id']      = (int)$rpacket_t_id;
        $where['rpacket_owner_id']  = (int)$member_id;
        $redpacket_count = $this->getRedpacketCount($where);
        if ($share_number <=  $redpacket_count) {
            $this->setErrorInfo('抱歉，领取额度已超限');
            return $result;
        }
        return $share_number;
    }

    /**
     * 检查分享红包的次数限制 -- 分享引流决定额度
     * @return false - 超限/ int - 可领取额度
     */
    public function checkShareRedpacketNumberAstrictDrainage($member_id = 0, $rpacket_t_id = 0)
    {
        $result = false;
        //判断红包分享表中是否存在由该分享引流的记录
        $model_redacket_share = Model('redpacket_share');
        $drainage_count = $model_redacket_share->countDrainageQuantity($member_id, $rpacket_t_id);
        //领取分享红包次数限制 -- 引流数量 + 1(自身分享)
        $get_rpacket_astrict = $drainage_count + 1;

        //查询该用户领取了多少红包
        $where = array();
        $where['rpacket_t_id']      = $tid;
        $where['rpacket_owner_id']  = $member_id;
        $redpacket_count = $this->getRedpacketCount($where);

        if ($get_rpacket_astrict <=  $redpacket_count) {
            $this->setErrorInfo('抱歉，领取额度已超限');
            return $result;
        }

        return $get_rpacket_astrict;
    }

    /**
     * 是否具有领取新人红包的权限
     * @param  int $member_id 会员id
     * @return array
     */
    public function newbieRedpacketJurisdiction($member_id)
    {
        $model_member = Model('member');
        $if_newbie = $model_member->checkIfNewbie($member_id);
        if ($if_newbie !== true) {
            return ['state' => false, 'msg' => $model_member->getErrorInfo()];
        }
        //是否获取过新人红包
        $redpacket_type_arr = $this->redpacket_type_arr;
        $rpacket_t_type = isset($redpacket_type_arr['newbie']['sign']) ? $redpacket_type_arr['newbie']['sign'] : 0;
        if (!$rpacket_t_type) return ['state' => false, 'msg' => '抱歉，红包类型错误'];

        $map = array(
            'rpacket_type' => $rpacket_t_type,
            'rpacket_owner_id' => (int)$member_id
        );
        $redpacket_count = $this->getRedpacketCount($map);
        if ($redpacket_count > 0) return ['state' => false, 'msg' => '抱歉，新人红包只能领取一个'];

        return ['state' => true, 'msg' => '可以领取'];
    }


    /**
     * 得到新人红包模板模板列表
     * @param  string $place_type 投放位置
     * @return array
     */
    public function newbieRedpacketLists($place_type)
    {
        $field = 'rpacket_t_id,rpacket_t_title,rpacket_t_desc,rpacket_t_start_date,rpacket_t_end_date,rpacket_t_price_type,rpacket_t_price,rpacket_t_price_state,rpacket_t_price_end,rpacket_t_limit,rpacket_t_total,rpacket_t_giveout,rpacket_t_customimg,rpacket_t_mgradelimit';
        //红包投放位置
        $place = array();
        $place_type_arr = array('all', $place_type);
        $rpacket_place = $this->rpacket_place;
        foreach ($place_type_arr as $place_type) {
            if (isset($rpacket_place[$place_type]['sign'])) $place[] = $rpacket_place[$place_type]['sign'];
        }

        //红包模板类型
        $redpacket_type_arr = $this->redpacket_type_arr;
        $rpacket_t_type = isset($redpacket_type_arr['newbie']['sign']) ? $redpacket_type_arr['newbie']['sign'] : 0;

        //红包模板状态
        $templatestate_arr = $this->templatestate_arr;
        $rpacket_t_state = isset($templatestate_arr['usable']['sign']) ? $templatestate_arr['usable']['sign'] : 0;

        $map = array(
            'rpacket_t_place' => array('in', $place),
            'rpacket_t_type' => array('eq', $rpacket_t_type),
            'rpacket_t_start_date' => array('elt', TIMESTAMP),
            'rpacket_t_end_date' => array('egt', TIMESTAMP),
            'rpacket_t_state' => array('eq', $rpacket_t_state)
        );
        $redpacket_lists = $this->getRptTemplateList($map, $field);
        return $redpacket_lists;
    }

    /**
     * 得到红包模版列表
     * @param  array  $condition 条件
     * @return array
     */
    public function getRedpacketLists($condition = array())
    {
        $field = 'rpacket_t_id,rpacket_t_place,rpacket_t_type,rpacket_t_title,rpacket_t_desc,rpacket_t_start_date,rpacket_t_end_date,rpacket_t_price_type,rpacket_t_price,rpacket_t_price_state,rpacket_t_price_end,rpacket_t_limit,rpacket_t_total,rpacket_t_giveout,rpacket_t_customimg,rpacket_t_gettype,rpacket_t_mgradelimit';
        $map = array();

        //红包投放位置
        $place = array();
        if (isset($condition['place_type'])) {
            $place_type = strtolower($condition['place_type']);
            $place_type_arr = ($place_type === 'all') ? array('all') : array('all', $place_type);
            $rpacket_place = $this->rpacket_place;
            foreach ($place_type_arr as $place_type) {
                if (isset($rpacket_place[$place_type]['sign'])) $place[] = $rpacket_place[$place_type]['sign'];
            }
            if ($place) $map['rpacket_t_place'] = array('in', $place);
        }

        //红包模板类型
        if (isset($condition['rpacket_t_type'])) {
            $rpacket_t_type = explode(',', $condition['rpacket_t_type']);
            $redpacket_type_arr = $this->getRedpacketType();
            $rpacket_type = array();
            foreach ($rpacket_t_type as $query_type) {
                if (isset($redpacket_type_arr[$query_type]['sign'])) $rpacket_type[] = $redpacket_type_arr[$query_type]['sign'];
            }
            if ($rpacket_type) $map['rpacket_t_type'] = array('in', $rpacket_type);
        }

        //红包领取方式
        if (isset($condition['get_type'])) {
            $get_type = explode(',', $condition['get_type']);
            $gettype_arr = $this->gettype_arr;
            $rpacket_t_gettype = array();
            foreach ($get_type as $query_type) {
                if (isset($gettype_arr[$query_type]['sign'])) $rpacket_t_gettype[] = $gettype_arr[$query_type]['sign'];
            }
            if ($rpacket_t_gettype) $map['rpacket_t_gettype'] = array('in', $rpacket_t_gettype);
        }

        //必要条件
        $map['rpacket_t_start_date'] = array('elt', TIMESTAMP);
        $map['rpacket_t_end_date'] = array('egt', TIMESTAMP);
        $map['rpacket_t_state'] = array('eq', self::RPACKET_STATE_USABLE);

        $redpacket_lists = $this->getRptTemplateList($map, $field);

        return $redpacket_lists;
    }


    /**
     * 获取红包模板总金额
     * @param $condition
     * @return string
     */
    public function getRedpacketTemplateamount($condition){
        $res = $this->table('redpacket_template')->where($condition)->sum('if(rpacket_t_price_type=1,rpacket_t_price*rpacket_t_eachlimit,(rpacket_t_price_state+rpacket_t_price_end)/2*rpacket_t_eachlimit)');
        return number_format(floatval(array_keys($res)[0]),2);
    }

    /**
     * 加密红包分享参数
     * @param  int $member_id    会员id
     * @param  int $rpacket_t_id 红包模板id
     * @return string
     */
    public function encryptParameter($member_id, $rpacket_t_id, $salt = 'oH#df15ax')
    {
        $encrypt_member = encrypt($member_id, $salt);
        $contrast_parameter = encrypt(md5($member_id.$salt.$rpacket_t_id), $salt);
        return ['redpacket_share_person' => $encrypt_member, 'redpacket_share_secretkey' => $contrast_parameter];
    }

    /**
     * 解密红包分享参数
     * @param  string $encrypt_member        加密的会员id
     * @param  string $contrast_parameter    对比数据
     * @param  int $rpacket_t_id 红包模板id
     * @param  string $salt                  加密时使用的盐
     * @return array / false
     */
    public function decryptParameter($encrypt_member, $contrast_parameter, $rpacket_t_id, $salt = 'oH#df15ax')
    {
        $member_id = decrypt($encrypt_member, $salt);
        $contrast_secret = md5($member_id.$salt.$rpacket_t_id);
        $temporary_secret =  decrypt($contrast_parameter, $salt);
        if ($temporary_secret !== $contrast_secret) return false;
        return ['member_id' => $member_id];
    }

    /**
     * 获取领取了该模板红包的用户
     * @param  integer $rpacket_t_id 红包模板id
     * @param  integer $member_id    会员id，若该次数不为0，则查出通过该用户分享红包模板链接方式领取的下属用户
     * @return array
     */
    public function getDrawRedpacketUser($rpacket_t_id = 0, $member_id = 0)
    {
        $member_id = 0; //因为现在红包分享，暂时没有记录层级关系
        $user_list = array();
        if (empty($member_id)) {    //查询模板下所有用户
            $field = 'member.member_avatar';
            $on = 'redpacket.rpacket_owner_id = member.member_id';
            $map = array(
                'redpacket.rpacket_t_id' => (int)$rpacket_t_id
            );
            $user_list = $this->table('redpacket,member')->field($field)->join('left')->on($on)->where($map)->group('redpacket.rpacket_owner_id')->select();

        } else {    //查询，通过该用户分享下属用户
            $field = 'member.member_avatar';
            $on = 'redpacket_share.rpacket_t_id = redpacket.rpacket_t_id AND redpacket_share.member_id = redpacket.rpacket_owner_id,redpacket.rpacket_owner_id = member.member_id';
            $map = array(
                'redpacket_share.rpacket_t_id' => (int)$rpacket_t_id,
                'redpacket_share.parent_member_id' => (int)$member_id
            );

            $user_list = $this->table('redpacket_share,redpacket,member')->field($field)->join('inner,left')->on($on)->where($map)->group('redpacket.rpacket_owner_id')->select();
        }   

        //处理用户列表
        is_array($user_list) &&  array_walk($user_list, function(&$item, $keys){
            $item['member_avatar_url'] = getMemberAvatar($item['member_avatar']);
        });
        return $user_list;
    }

}